package com.example.xgsweather.service;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.widget.RemoteViews;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.example.xgsweather.R;
import com.example.xgsweather.activity.MainActivity;
import com.example.xgsweather.util.HttpUtil;
import com.example.xgsweather.util.LogUtil;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.weather.WeatherNowBean;
import com.qweather.sdk.view.QWeather;

import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherNotificationsService extends Service {

    private static final String TAG = "WeatherNotificationsSer测试";

    private static final String CHANNEL_ID = "XgsWeatherServiceChannel";
    private static final int NOTIFICATION_ID = 2001;

    private Timer mTimer = null;
    private NotificationCompat.Builder mBuilder;
    private NotificationManager mNotificationManager;
    private RemoteViews mRemoteViews;
    private String mCityName;
    private String mTemperature;
    private String mWeather;

    @Override
    public void onCreate() {
        LogUtil.d(TAG + " onCreate: do");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.d(TAG + " onStartCommand: do");
        init();
        getWeather(intent);
        startTimer();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        LogUtil.d(TAG + " onDestroy: do");
        stopTimer();
        super.onDestroy();
        mNotificationManager.cancel(NOTIFICATION_ID);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 初始化
     */
    private void init() {
        mRemoteViews = new RemoteViews(getPackageName(), R.layout.notifications_weather);
        mNotificationManager = getSystemService(NotificationManager.class);
        // 创建通知信道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_DEFAULT
            );
            mNotificationManager.createNotificationChannel(serviceChannel);
        }
        // 创建一个 Intent 对象，指向应用程序的启动活动
        Intent launchIntent = new Intent(this, MainActivity.class);
        launchIntent.setAction(Intent.ACTION_MAIN);
        launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, launchIntent, PendingIntent.FLAG_MUTABLE);
        // 创建前台服务的通知
        mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setCustomBigContentView(mRemoteViews)
                .setContentIntent(pendingIntent)
                .setAutoCancel(false)
                .setSmallIcon(R.drawable.logo)
                .setOnlyAlertOnce(true);
        startForeground(NOTIFICATION_ID, mBuilder.build());
    }

    /**
     * 获取天气信息
     *
     * @param intent 携带weather_id的intent
     */
    private void getWeather(Intent intent) {
        LogUtil.d("update weather");
        SharedPreferences prefs = getSharedPreferences("current_city", Context.MODE_PRIVATE);
        String mWeatherId = null;
        if (prefs.getString("weather_id", null) != null) {
            mWeatherId = prefs.getString("weather_id", null);
            mCityName = prefs.getString("county_name", null);
        } else if (intent != null) {
            mWeatherId = intent.getStringExtra("weather_id");
            mCityName = intent.getStringExtra("county_name");
        }
        if (mWeatherId == null || "".equals(mWeatherId)) {
            return;
        }
        // 查询当前天气
        QWeather.getWeatherNow(getApplicationContext(), mWeatherId, new QWeather.OnResultWeatherNowListener() {
            @Override
            public void onError(Throwable e) {
                LogUtil.w(TAG + " getWeather onError: " + e);
            }

            @Override
            public void onSuccess(WeatherNowBean weatherBean) {
                //先判断返回的status是否正确，当status正确时获取数据，若status不正确，可查看status对应的Code值找到原因
                if (Code.OK == weatherBean.getCode()) {
                    WeatherNowBean.NowBaseBean now = weatherBean.getNow();
                    mTemperature = now.getTemp();
                    mWeather = now.getText();
                    updatePig();
                } else {
                    //在此查看返回数据失败的原因
                    Code code = weatherBean.getCode();
                    LogUtil.w(TAG + "WeatherActivity failed code: " + code);
                }
            }
        });
    }

    /**
     * 开始定时任务
     */
    private void startTimer() {
        stopTimer();
        LogUtil.d("startTimer");
        mTimer = new Timer();
        mTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                new Handler(getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        // TODO: 2023/6/7 添加一个设置，是否在通知栏显示天气
                        /*SharedPreferences prefs = getSharedPreferences("app_settings", Context.MODE_PRIVATE);
                        if (!prefs.getBoolean("is_show_notification", true)) {
                            stopSelf();
                        }*/
                        // 更新天气信息
                        getWeather(null);
                    }
                });
            }
        }, 60 * 1000, 60 * 60 * 1000);
    }

    /**
     * 停止定时任务和通知
     */
    private void stopTimer() {
        try {
            if (mTimer != null) {
                mTimer.cancel();
                mTimer = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新通知的背景图片
     */
    private void updatePig() {
        HttpUtil.sendOkHttpRequest(HttpUtil.requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtil.e(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = response.body().byteStream();
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                mRemoteViews.setImageViewBitmap(R.id.notification_bg, bitmap);
                // 更新通知栏内容
                updateNotification();
            }
        });
    }

    /**
     * 更新通知栏
     */
    private void updateNotification() {
        LogUtil.d("updateNotification");
        // 更新 RemoteViews 上的天气信息
        mRemoteViews.setTextViewText(R.id.city_name, mCityName);
        mRemoteViews.setTextViewText(R.id.city_temperature, mTemperature + "℃");
        mRemoteViews.setTextViewText(R.id.city_weather_info, mWeather);
        // 更新通知栏内容
        mBuilder.setContent(mRemoteViews);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        // 发送广播更新桌面小组件内容
        sendBroadcast(new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE));
    }

}

